// auth守卫
import {
  CanActivate,
  ExecutionContext,
  Inject,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { jwtConstants } from '../api/auth/constants';
import { Request } from 'express';
import { Reflector } from '@nestjs/core';
import { JwtBlacklistService } from '@/api/auth/jwt-blacklist.service';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private reflector: Reflector,
    private jwtService: JwtService,
    @Inject(JwtBlacklistService)
    private readonly jwtBlacklistService: JwtBlacklistService,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    // 如果使用了skipAuth，则跳过jwt验证
    const isSkip = this.reflector.get<boolean>(
      'skipAuth',
      context.getHandler(),
    );

    if (isSkip) {
      return true;
    }

    const request = context.switchToHttp().getRequest();
    const token = this.extractTokenFromHeader(request);
    if (!token) {
      throw new UnauthorizedException();
    }
    // 黑名单校验
    if (this.jwtBlacklistService.isTokenRevoked(`Bearer ${token}`)) {
      throw new UnauthorizedException();
    }
    try {
      const payload = await this.jwtService.verifyAsync(token, {
        secret: jwtConstants.secret,
      });
      request['user'] = payload;
    } catch {
      throw new UnauthorizedException();
    }
    return true;
  }

  private extractTokenFromHeader(request: Request): string | undefined {
    const [type, token] = request.headers.authorization?.split(' ') ?? [];
    return type === 'Bearer' ? token : undefined;
  }
}
